package edu.cuit.avatar.common;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/28 10:21
 */
public class MybatisHelper {
    private static SqlSessionFactory factory;

    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();

    static{
        try {
            var reader = Resources.getResourceAsReader("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSessionFactory getSqlSessionFactory(){
        return factory;
    }

    public static SqlSession openSession(){
        //从当前线程中取绑定的本地变量SqlSession
        SqlSession session = tl.get();
        if(session == null){
            session = factory.openSession(false);
            //绑定session到当前线程
            tl.set(session);
        }
        return session;
    }

    public static SqlSession openSession(boolean autoCommit){
        //从当前线程中取绑定的本地变量SqlSession
        SqlSession session = tl.get();
        if(session == null){
            session = factory.openSession(autoCommit);
            //绑定session到当前线程
            tl.set(session);
        }
        return session;
    }

    public static void close(){
        SqlSession session = tl.get();
        if(session != null){
            session.close();
        }
        //从当前线程中移除绑定的数据SqlSession
        tl.remove();
    }
}
